//
//  ColorUtil.swift
//  Extend
//
//  Created by shufang zou on 2017/8/22.
//  Copyright © 2017年 敬信. All rights reserved.
//

import Foundation


public extension UIColor {
    
    //    #pragma mark - Hex 十六进制返回颜色
    public class func HexString(_ color:String,  alpha:CGFloat) -> UIColor{
        
        return colorString(colorStr:color,alpha:alpha);
    }
    
    public class func HexString(_ color:String) -> UIColor{
        
        return colorString(colorStr:color,alpha:1);
    }
    
    
    //    #pragma mark - RGB 数字返回颜色
    public class func RGBHexNum(_ num:CGFloat, alpha:CGFloat) -> UIColor{
        let red: CGFloat = num / (256.0 * 256.0)
        let green: CGFloat = (num.truncatingRemainder(dividingBy:  (256.0 * 256.0))) / 256.0
        let blue: CGFloat = num.truncatingRemainder(dividingBy: 256.0)
        
        return UIColor(red: red / 255.0, green: green / 255.0, blue: blue / 255.0, alpha: alpha)
    }
}



/// Hex 十六进制返回颜色
///
/// - Parameters:
///   - colorStr: 十六进制字符串
///   - alpha: 透明度
/// - Returns: color


private func colorString(colorStr:String, alpha:CGFloat) -> UIColor{
    var color = UIColor.clear
    var cStr : String = colorStr.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()
    
    if cStr.hasPrefix("#") {
        let index = cStr.index(after: cStr.startIndex)
        cStr = cStr.substring(from: index)
    }
    if cStr.hasPrefix("0X") {
        let index = cStr.index(after: cStr.startIndex)
        cStr = cStr.substring(from: index)
    }
    if cStr.count != 6 {
        return UIColor.clear
    }
    
    let rRange = cStr.startIndex ..< cStr.index(cStr.startIndex, offsetBy: 2)
    let rStr = cStr.substring(with: rRange)
    
    let gRange = cStr.index(cStr.startIndex, offsetBy: 2) ..< cStr.index(cStr.startIndex, offsetBy: 4)
    let gStr = cStr.substring(with: gRange)
    
    let bIndex = cStr.index(cStr.endIndex, offsetBy: -2)
    let bStr = cStr.substring(from: bIndex)
    
    color = UIColor(red: CGFloat(changeToInt(numStr: rStr)) / 255, green: CGFloat(changeToInt(numStr: gStr)) / 255, blue: CGFloat(changeToInt(numStr: bStr)) / 255, alpha: alpha);
    
    return color
}


private func changeToInt(numStr:String) -> Int {
    let str = numStr.uppercased()
    var sum = 0
    for i in str.utf8 {
        sum = sum * 16 + Int(i) - 48
        if i >= 65 {
            sum -= 7
        }
    }
    return sum
}





